<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
<script>
    const data = [{
        id: 2,
        pid: 0,
        path: '/course',
        name: 'Course',
        title: '课程管理'
    }, {
        id: 3,
        pid: 2,
        path: '/operate',
        name: 'CourseOperate',
        title: '课程操作'
    }, {
        id: 4,
        pid: 3,
        path: '/course',
        name: 'CourseInfoData',
        title: '课程数据'
    }, {
        id: 5,
        pid: 2,
        path: '/course/add',
        name: 'CourseAdd',
        title: '增加课程'
    }, {
        id: 6,
        pid: 0,
        path: '/student',
        name: 'student',
        title: '学生管理'
    }, {
        id: 7,
        pid: 6,
        path: '/operate',
        name: 'StudentOperate',
        title: '学生操作'
    }, {
        id: 8,
        pid: 6,
        path: '/add',
        name: 'StudentAdd',
        title: '增加学生'
    }];

    // 采用递归的方式
    function formatDataTree() {
        let parents = data.filter(p => p.pid === 0);
        let children = data.filter(p => p.pid !== 0);

        dataToTree(parents, children);
        return parents

        function dataToTree(parents, children) {
            parents.map(p => {
                children.map((c, i) => {
                    if (p.id === c.pid) {
                        let _children = JSON.parse(JSON.stringify(children))
                        _children.splice(i, 1)
                        dataToTree([c], _children)
                        if (p.children) {
                            p.children.push(c)
                        } else {
                            p.children = [c]
                        }
                    }
                })
            })
        }

    }

    const treeData = formatDataTree()
    console.log(treeData)
</script>
</body>

</html>
